package com.lm.activiti.boot.tools.qrcode;

import com.google.common.collect.ImmutableMap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Base64;

/**
 *
 * 二维码操作
 *
 * @author lm_jcf
 * @date 2020/8/28 16:02
 */
public class QrCodeUtils {

    public static void main(String[] args) throws IOException, WriterException {
//        createQrCodeImage();

        generateQRCodeImage("http://csm.52ess.cn/qrcode/newPay?schoolId=" + 21966 + "&bizCode=" + "2BpVeH2kTuw" + "&templateId=", 300, 300, "D:\\qrcode.png");
    }

    public static void createQrCodeImage() throws WriterException, IOException {

        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        int width = 300;
        int height = 300;

        BitMatrix bitMatrix = qrCodeWriter.encode("法克", BarcodeFormat.QR_CODE, width, height,
                ImmutableMap.of(EncodeHintType.CHARACTER_SET, "UTF-8"
                        , EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M,
                        EncodeHintType.MARGIN, 2));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        byte[] qrcodeDatas = outputStream.toByteArray();

        byte[] encode = Base64.getEncoder().encode(qrcodeDatas);

        System.out.println("data:image/png;base64,"+new String(encode, "UTF-8"));
    }

    public static void generateQRCodeImage(String contents, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, width, height,
                ImmutableMap.of(EncodeHintType.CHARACTER_SET, "UTF-8"
                        , EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M,
                        EncodeHintType.MARGIN, 2));

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(filePath));
    }
}
